package com.example.ywr.service.impl;

import com.example.ywr.common.PageParam;
import com.example.ywr.common.PageResult;
import com.example.ywr.entity.Category;
import com.example.ywr.repository.CategoryRepository;
import com.example.ywr.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 商品分类服务实现类
 */
@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Category add(Category category) {
        return categoryRepository.save(category);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Category update(Category category) {
        Optional<Category> optional = categoryRepository.findById(category.getId());
        if (optional.isPresent()) {
            Category existCategory = optional.get();
            // 更新分类信息
            existCategory.setName(category.getName());
            existCategory.setDescription(category.getDescription());
            existCategory.setParentId(category.getParentId());
            existCategory.setLevel(category.getLevel());
            existCategory.setSort(category.getSort());
            existCategory.setStatus(category.getStatus());
            return categoryRepository.save(existCategory);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        Optional<Category> optional = categoryRepository.findById(id);
        if (optional.isPresent()) {
            Category category = optional.get();
            category.setIsDeleted(true);
            categoryRepository.save(category);
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDelete(List<Long> ids) {
        List<Category> categories = categoryRepository.findAllById(ids);
        if (!categories.isEmpty()) {
            categories.forEach(category -> category.setIsDeleted(true));
            categoryRepository.saveAll(categories);
            return true;
        }
        return false;
    }

    @Override
    public Category getById(Long id) {
        Optional<Category> optional = categoryRepository.findById(id);
        return optional.orElse(null);
    }

    @Override
    public PageResult<Category> list(PageParam pageParam) {
        Sort sort = Sort.by(Sort.Direction.fromString(pageParam.getOrderDirection()), 
                pageParam.getOrderBy() != null ? pageParam.getOrderBy() : "sort");
        Pageable pageable = PageRequest.of(pageParam.getPageNum() - 1, pageParam.getPageSize(), sort);
        Page<Category> page = categoryRepository.findAll(pageable);
        return PageResult.fromPage(page);
    }

    @Override
    public List<Category> listByParentId(Long parentId) {
        return categoryRepository.findByParentIdAndIsDeletedFalse(parentId);
    }

    @Override
    public List<Category> listByLevel(Integer level) {
        return categoryRepository.findByLevelAndIsDeletedFalse(level);
    }

    @Override
    public PageResult<Category> listByName(String name, PageParam pageParam) {
        Sort sort = Sort.by(Sort.Direction.fromString(pageParam.getOrderDirection()), 
                pageParam.getOrderBy() != null ? pageParam.getOrderBy() : "sort");
        Pageable pageable = PageRequest.of(pageParam.getPageNum() - 1, pageParam.getPageSize(), sort);
        Page<Category> page = categoryRepository.findByNameContainingAndIsDeletedFalse(name, pageable);
        return PageResult.fromPage(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(Long id, Integer status) {
        int rows = categoryRepository.updateStatus(id, status);
        return rows > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchUpdateStatus(List<Long> ids, Integer status) {
        int rows = categoryRepository.batchUpdateStatus(ids, status);
        return rows > 0;
    }
}